<template>
  <div>
    <el-group-title class="d_jump">
      <template slot="groupTitle">
        <el-form
          :model="form"
          ref="form"
          label-width="160px"
          class="ccui-form"
          :rules="rules"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="填报单位：" prop="reportInOrgName">
                <el-select
                  v-model="form.reportInOrgName"
                  placeholder="请选择填报单位"
                  @change="changeReportInOrgId"
                >
                  <el-option
                    v-for="item in reportOptions"
                    :key="item.orgId"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="部门：" prop="department">
                <el-select
                  ref="selectTree"
                  v-model="form.department"
                  placeholder="请选择部门"
                  popper-class="popperTreeSelect"
                >
                  <el-option label="" value="">
                    <el-tree
                      :data="departOptions"
                      :props="{ children: 'child', label: 'abbrName' }"
                      @node-click="handleNodeClick"
                    >
                      <!-- <span class="custom-tree-node" slot-scope="{ node }">
                    <i :class="iconClass(node.data)" class="orgIcon" />
                    {{ node.data.abbrName }}
                  </span> -->
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称：" prop="projectName">
                <el-input
                  v-model="form.projectName"
                  placeholder="请输入项目名称"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="供应商：" prop="supplierName">
                <el-input
                  v-model="form.supplierName"
                  placeholder="请输入供应商"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="入库单编号：" prop="storageCode">
                <el-input
                  v-model="form.storageCode"
                  placeholder="请输入入库单编号"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="入库单名称：" prop="storageName">
                <el-input
                  v-model="form.storageName"
                  placeholder="请输入入库单名称"
                  maxlength="300"
                  show-word-limit
                  @blur="handleTrim('storageName')"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="结算单编号：" prop="settlementCode">
                <el-row class="el-col-20" :gutter="20">
                  <el-col :span="17">
                    <el-input
                      v-model="form.settlementCode"
                      placeholder="请选择结算单编号"
                      disabled
                    ></el-input>
                  </el-col>
                  <el-col :span="3">
                    <codeNumber
                      :reportInOrgId="this.form.reportInOrgId"
                      @inventoryConfirm="codeNumberInventoryConfirm"
                      :isTrue="false"
                    ></codeNumber>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="结算单名称：" prop="settlementName">
                <el-input
                  v-model="form.settlementName"
                  placeholder="请输入结算单名称"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="仓库：" prop="warehouseName">
                <el-input
                  v-model="form.warehouseName"
                  placeholder="请选择仓库"
                  disabled
                ></el-input>
                <warehouseDialog
                  @numrow="numrow"
                  :reportInOrgName="form.reportInOrgName"
                  :reportInOrgId="form.reportInOrgId"
                  :isTrue="false"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="物资来源：" prop="materialForm">
                <el-input
                  v-model="form.materialForm"
                  placeholder="请输入物资来源"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="计税方式：" prop="valoremMethod">
                <el-input
                  v-model="form.valoremMethod"
                  placeholder="请输入计税方式"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="本位币币种：" prop="standardMoney">
                <el-input
                  v-model="form.standardMoney"
                  placeholder="请输入本位币币种"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="入库数量：" prop="storageCount">
                <el-input
                  v-model="form.storageCount"
                  placeholder="请输入入库数量"
                  @keyup.native="form.storageCount = oninput(form.storageCount)"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="入库金额：" prop="storageMoney">
                <el-input
                  v-model="form.storageMoney"
                  placeholder="请输入入库金额"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="入库类型：" prop="storageType">
                <el-select
                  v-model="form.storageType"
                  class="ccui-form-longInput"
                  placeholder="请选择入库类型"
                  disabled
                >
                  <el-option
                    v-for="(item, index) in storageTypeList"
                    :key="index"
                    :label="item.dicValue"
                    :value="item.dicKey"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="附件张数：" prop="fileNum">
                <el-input
                  v-model="form.fileNum"
                  placeholder="请输入附件张数"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="编制人：" prop="reportUsername">
                <el-input
                  v-model="form.reportUsername"
                  placeholder="请输入编制人"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="编制日期：" prop="reportTime">
                <el-input
                  v-model="form.reportTime"
                  placeholder="请输入编制日期"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="13">
              <el-form-item label="业务事由：" prop="businessReasons">
                <el-input
                  class="remarkClass"
                  resize="both"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入业务事由"
                  maxlength="400"
                  show-word-limit
                  v-model="form.businessReasons"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="13">
              <el-form-item label="备注：" prop="remark">
                <el-input
                  class="remarkClass"
                  resize="both"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入备注"
                  maxlength="1000"
                  show-word-limit
                  v-model="form.remark"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </el-group-title>
  </div>
</template>

<script>
import { addUrlPerFix } from "@/basa/utils";
import warehouseDialog from "@/app/inventoryManagement/components/warehouseDialog";
import codeNumber from "@/app/inventoryManagement/components/codeNumber";
import jsList from "@/app/inventoryManagement/js";
import { getUserInfo, getReportInOrgData, qryUnderOrg } from "@/basa/api";
import { getSettlementById } from "../../api/add-item";
// import { formatNumber } from "@/basa/utils";
import BigNumber from "bignumber.js";
export default {
  components: { codeNumber, warehouseDialog },
  props: {
    storageList: {
      type: Array,
    },
    storageForm: {
      type: Object,
    },
  },
  data() {
    return {
      form: {
        contractCode: "", //合同编号
        storageCode: "", //入库单编号
        storageName: "", //入库单名称
        settlementCode: "", //结算单编号
        settlementName: "", //结算单名称
        materialForm: "", //物资来源
        warehouseName: "", //仓库
        settlementCount: "", //结算数量
        storageCount: "", //入库数量
        storageMoney: "", //入库金额
        supplierName: "", //供应商名称
        reportInOrgName: "", // 填报单位
        thirdCategoriesOfName: "", // 分类名称
        reportUsername: "", // 编制人
        reportTime: "", //编制日期
        remark: "", // 备注
        storageType: "", //入库类型   1，财务入库；2，财务暂估入库
        settlementListId: "",
        valoremMethodCode: "", // 计税方法编码
        valoremMethod: "", // 计税方法
        businessReasons: "", // 业务事由
        standardMoneyCode: "", // 本位币编码
        standardMoney: "", // 本位币名称
        departCode: "", // 所属部门4A编码
        fileNum: "", // 附件张数
        projectName: "", // 项目名称
        projectCode: "", // 项目编码
        department: "", // 所属部门
        departmentId: "", // 所属部门ID
        departmentOrgId: "", // 所属部门单位ID
      },
      rules: {
        storageName: [
          { required: true, message: "请输入入库单名称", trigger: "blur" },
        ],
        settlementCode: [
          { required: true, message: "请选择结算单编号", trigger: "change" },
        ],
        warehouseName: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
        reportInOrgName: [
          { required: true, message: "请选择填报单位", trigger: "change" },
        ],
        department: [
          { required: true, message: "请选择部门", trigger: "change" },
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        valoremMethod: [
          { required: true, message: "请输入计税方式", trigger: "blur" },
        ],
        standardMoney: [
          { required: true, message: "请输入本位币币种", trigger: "blur" },
        ],
        fileNum: [
          { required: true, message: "请输入附件张数", trigger: "blur" },
        ],
        businessReasons: [
          { required: true, message: "请输入业务事由", trigger: "blur" },
        ]
      },
      tableData: [],
      storageTypeList: [
        { dicValue: "正式入库", dicKey: 1 },
        { dicValue: "暂估入库", dicKey: 2 },
        { dicValue: "入库冲销", dicKey: 3 },
      ],
      reportInOrgObj: {
        title: "填报单位查询",
        tableHeadOptions: jsList.reportInOrgTableHead,
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 20,
        },
      },
      reportOptions: [], // 填报单位
      departOptions: [], // 部门数据
      count: 0,
    };
  },
  watch: {
    "form.reportInOrgName": {
      handler(n) {
        if (n) {
          const tempObj = this.reportOptions.find((e) => e.name === n);
          if (tempObj) {
            this.form.reportInOrgId = tempObj.orgId;
            this.form.reportInOrgName = tempObj.name;
            this.getDepartData(tempObj.orgId);
          }
        }
      },
      immediate: true,
      deep: true,
    },
    $route(to, from) {
      if (
        from.name == "inventoryManagement-financialList-whole" ||
        from.name == "inventoryManagement-financialList-un-submitted" ||
        from.name == "inventoryManagement-financialList-under-approval" ||
        from.name == "inventoryManagement-financialList-return-approval"
      ) {
        this.addDate(); //获取当前日期
        this.form.storageType = "暂估入库";
      } else if (
        from.name == "inventoryManagement-financeWarehousing-whole" ||
        from.name == "inventoryManagement-financeWarehousing-un-submitted" ||
        from.name == "inventoryManagement-financeWarehousing-under-approval" ||
        from.name == "inventoryManagement-financeWarehousing-return-approval"
      ) {
        this.addDate(); //获取当前日期
        this.form.storageType = "正式入库";
      }
    },
    storageForm: {
      handler(newVal, oldVal) {
        if (newVal.settlementCount && newVal.moneyWithTax) {
          this.$nextTick(() => {
            this.$set(this.form, "storageCount", newVal.settlementCount);
            this.$set(this.form, "storageMoney", newVal.moneyWithTax);
          });
        } else {
          this.form.storageCount = "";
          this.form.storageMoney = "";
        }
      },
      deep: true,
    },
  },
  mounted() {
    if (sessionStorage.getItem("storageType") == 1) {
      // this.form.storageType = "正式入库";
      this.$set(this.form, "storageType", "正式入库");
    } else if (sessionStorage.getItem("storageType") == 2) {
      // this.form.storageType = "暂估入库";
      this.$set(this.form, "storageType", "暂估入库");
    }
  },
  created() {
    this.addDate();
    this.getUserInfo();
  },
  activated() {
    this.getUserInfo();
  },
  methods: {
    // 选择仓库 返回数据
    numrow(row) {
      console.log(row,">>>>>")
      this.form.warehouseId = row.id;
      this.form.warehouseCode = row.warehouseCode;
      this.form.warehouseName = row.warehouseName;
      this.form.projectName = row.projectName; // 项目名称
      this.form.projectCode = row.projectCode; // 项目编码
      this.form.valoremMethodCode = row.valoremMethodCode; // 计税方法编码
      this.form.valoremMethod = row.valoremMethod; // 计税方法
      this.form.standardMoneyCode = row.standardMoneyCode; // 本位币编码
      this.form.standardMoney = row.standardMoney; // 本位币名称
    },
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then((res) => {
        this.form.compileUser = res.data.data.userInfo.name;
        this.form.reportUsername = res.data.data.userInfo.name;
        this.userOpenId = res.data.data.userInfo.openId;
        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报信息
    getReportInOrgData(openId) {
      getReportInOrgData({ openIds: [openId] }).then((res) => {
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.form.reportInOrgName =
          this.form.reportInOrgName || this.reportOptions[0].name;
        this.form.reportInOrgId =
          this.form.reportInOrgId || this.reportOptions[0].orgId;
        
      });
    },
    // 填报单位
    changeReportInOrgId(val) {
      const tempObj = this.reportOptions.find((e) => e.name === val);
      this.form.reportInOrgId = tempObj.orgId;
      this.form.reportInOrgName = tempObj.name;

      // 改变填报单位清空 数据
      this.form.storageName = "";
      this.form.settlementCode = "";
      this.form.settlementName = "";
      this.form.supplierName = "";
      this.form.materialForm = "";
      this.form.warehouseName = "";
      this.form.storageCount = "";
      this.form.storageMoney = "";
      this.tableData = [];
      this.getDepartData(val);
      this.$emit("updataList", this.tableData);
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    // 部门 start
    async getDepartData(parentId) {
      const {
        child,
        child: [{ id, abbrName, autoCode }]
      } = (
        await qryUnderOrg({
          parentId: parentId, // 全局 其他【此组件是本级及以下】
          flag: "1" // 0 公司 1 部门 2 成员
        })
      ).data.data[0];
      this.departOptions = child;
      // 默认第一个部门
      this.form.departmentId = id;
      this.form.department = abbrName;
      this.form.departCode = autoCode;
    },

    // 部门选中的数据
    handleNodeClick(data) {
      this.form.departmentId = data.id;
      this.form.department = data.abbrName;
      this.form.departCode = data.autoCode;
      this.$refs.selectTree.blur();
    },
    // 部门 end
    codeNumberInventoryConfirm(data) {
      this.form.settlementId = data.id;
      this.form.settlementCode = data.settlementCode;
      this.form.settlementName = data.settlementName;
      this.form.contractId = data.contractId;
      this.form.contractCode = data.contractCode;
      this.form.contractName = data.contractName;
      this.form.supplierName = data.supplierName;
      this.form.supplierId = data.supplierId;
      this.form.supplierCode = data.supplierCode;
      this.form.settlementCount = data.currSetCount
        ? data.currSetCount.toFixed(3)
        : "";
      // this.form.storageCount = data.currSetCount.toFixed(3);
      this.form.storageMoney = data.currSetMoney
        ? data.currSetMoney.toFixed(2)
        : "";
      this.form.materialForm = data.materialSource;
      this.form.thirdCategoriesOfName = data.thirdCategoriesOfName;
      this.tableData = [];
      getSettlementById({
        ids: [data.id],
      }).then((res) => {
        res.data.data.settlementList.forEach((item, index) => {
          // item.
          item.settlementListId = item.id;
          if (item.isMerge == 0 || item.isMainInventory == 1) {
            item.materialFirstId = item.materialFirstId || 0;
            if (+item.isOtherCost == 0 && +item.isServices == 0) {
              item.unStorageCount = item.unStorageCount
                ? item.unStorageCount.toFixed(3)
                : "";
              item.settlementCount = item.settlementCount
                ? item.settlementCount.toFixed(3)
                : "";
              item.count = item.settlementCount;
              item.storageCount = item.unStorageCount
                ? item.unStorageCount
                : "";
              item.unitPriceWithTax = item.unitPriceWithTax
                ? item.unitPriceWithTax.toFixed(2)
                : "";

              // 计算含税金额
              item.moneyWithTax = new BigNumber(
                Number(item.unitPriceWithTax)
              ).multipliedBy(Number(item.storageCount));
            }
            if (+item.isOtherCost == 1 || +item.isServices == 1) {
              item.storageCount = "";
              item.unStorageCount = "";
              item.unitPriceWithTax = "";
              if (item.relationList && item.relationList.length > 0) {
                let newList = [];
                item.relationList.forEach((val) => {
                  val.pkPurmatdetl = val.id;
                  newList.push(val.storageCode);
                });
                item.relationCode = newList.join(",");
              } else {
                item.relationList = [];
              }
            }

            // item.settlementListId = item.id;
            item.moneyWithTax = item.moneyWithTax
              ? item.moneyWithTax.toFixed(2)
              : "";
            // item.moneyWithoutTax = item.moneyWithoutTax.toFixed(2);
            let taxRate = new BigNumber(Number(item.taxRate))
              .plus(1)
              .toString();
            // item.moneyWithoutTax = (
            //   item.moneyWithTax /
            //   (1 + Number(item.taxRate))
            // ).toFixed(2);
            item.moneyWithoutTax = new BigNumber(
              Number(item.moneyWithTax)
            ).dividedBy(taxRate);
            item.moneyWithoutTax = item.moneyWithoutTax
              ? item.moneyWithoutTax.toFixed(2)
              : "";
            this.tableData.push(item);
          }
        });
      });
      this.$emit("updataList", this.tableData);
      this.$emit("updataForm", this.form);
    },
    oninput(num) {
      if (num <= this.count) {
        //      debugger
        //正则替换
        //后来调试发现这个函数只能用于字符串，当是数字的时候就会报此错误
        var str = num.toString();
        str = str.replace(/[^\d.]/g, ""); // 保留数字   /[^\d.]/g, ""
        str = str.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        return str;
      } else {
        return this.count;
      }
    },
    handleSelect() {
      this.$refs["brachFormVisible"].dialogVisible = true;
    },
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate(),
      };
      if (String(date.month).length == 1) {
        date.month = "0" + date.month;
      }
      if (String(date.date).length == 1) {
        date.date = "0" + date.date;
      }
      this.form.reportTime = date.year + "-" + date.month + "-" + date.date;
    },
    // input 输入框去掉前后空格
    handleTrim(key) {
      this.$set(this.form, key, this.form[key].replace(/(^\s*)|(\s*)$/g, ""));
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-input {
  width: 260px;
}

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}
/deep/.ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}
/deep/.el-col-12 {
  width: 50%;
}
/deep/.el-col-13 {
  width: 100%;
}
/deep/.el-textarea {
  width: 760px;
}
.remarkClass {
  width: calc(50% + 343px);
}
/deep/.el-col-20 {
  display: flex;
}
/deep/.el-col-17 {
  width: 260px;
  margin-right: 5px;
}
::v-deep {
  .el-input input {
    padding-right: 50px;
  }
}
</style>
